<template>
  <DialogForm ref="dialogFormRef" />
  <el-card :border="false" style="margin-bottom: 15px;">
    <div class="items-center">
      <StatisticCard style="width: 60%;" />
      <el-button type="primary" @click="getAllData()">
        <el-icon>
        </el-icon>
        全部
      </el-button>
    </div>

  </el-card>
  <el-card :border="false">
    <el-table :data="tableData" border style="width: 100%;" v-loading="loading">
      <el-table-column label="git项目名称" prop="project_name" />
      <el-table-column label="项目所有者邮箱" prop="project_owner_email" />
      <!--  -->
      <el-table-column label="项目作者详情">
        <template v-slot="scope">
          <a :href="scope.row.project_owner_html_url" style="color: blue; text-decoration: underline;" target="_blank">
            {{ shortenUrl(scope.row.project_owner_html_url) }}
          </a>
        </template>
      </el-table-column>

      <!--  -->
      <el-table-column label="项目git地址">
        <template v-slot="scope">
          <a :href="scope.row.project_git_url" style="color: blue; text-decoration: underline;" target="_blank">
            {{ shortenUrl(scope.row.project_git_url) }}
          </a>
        </template>
      </el-table-column>
      <!--  -->
      <el-table-column label="项目仓库地址">
        <template v-slot="scope">
          <a :href="scope.row.repository_git_http_url" style="color: blue; text-decoration: underline;" target="_blank">
            {{ shortenUrl(scope.row.repository_git_http_url) }}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="项目语言" prop="project_language" color="red" />
      <!--  -->
      <el-table-column label="查看项目端口">
        <template v-slot="scope">
          <el-button type="success" @click="viewPort(scope.row.project_git_url)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template v-slot="scope">
          <div style="display: flex;justify-content: space-around;">
            <el-button type="success" @click="viewEmission(scope.row)">查看</el-button>
            <template v-if="user_id === scope.row.captain_id">
              <el-button type="danger" @click="deploy(scope.row)">部署</el-button>
            </template>

          </div>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页器 -->
    <el-row style="width: 100%; align-items: center;justify-content: center;margin-top: 20px;">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30]"
        :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
  </el-card>
  <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :title="dialogTitle" width="40%"
    @close="closeDialogForm('form')">
    <el-form ref="ruleFormRef" :model="form" label-width="auto" style="max-width: 600px">

      <el-form-item label="Git 项目名称" prop="project_name">
        <el-input v-model="form.project_name" readonly></el-input>
      </el-form-item>
      <el-form-item label="项目所有者邮箱" prop="project_owner_email">
        <el-input v-model="form.project_owner_email" readonly></el-input>
      </el-form-item>
      <el-form-item label="项目作者详情" prop="project_owner_html_url">
        <el-input v-model="form.project_owner_html_url" readonly></el-input>
      </el-form-item>
      <el-form-item label="项目 Git 地址" prop="project_git_url">
        <el-input v-model="form.project_git_url" readonly></el-input>
      </el-form-item>
      <el-form-item label="项目仓库地址" prop="repository_git_http_url">
        <el-input v-model="form.repository_git_http_url" readonly></el-input>
      </el-form-item>
      <el-form-item label="修改前后对比" prop="commits_url">
        <el-input v-model="form.commits_url" readonly></el-input>
      </el-form-item>
      <el-form-item label="项目语言" prop="project_language">
        <el-input v-model="form.project_language" readonly></el-input>
      </el-form-item>


      <el-form-item>
        <el-button @click="closeDialogForm('form')">取消</el-button>
      </el-form-item>

    </el-form>
  </el-dialog>
</template>

<script lang="js" setup>

import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import DialogForm from '../components/form/AddNewProject.vue'
import StatisticCard from '../components/StatisticCard.vue'
import axios from 'axios'

const currentPage = ref(1)
const pageSize = ref(10)
//记录请求返回数据的集合
const msg = ref([]);

//用于记录用户所查询的输入信息 inputStr
const inputStr = ref()

//用于暂存当前页的数据
const tableData = ref([])
tableData.value = msg.value

let total = ref(tableData.value.length)
let user_id
let loading = ref(false)

// 获取所有的数据
function getData() {
  axios.get('project/getResource')
    .then(response => {
      // 请求成功的处理
      // 把数据传给 msg 数组
      msg.value = response.git_pro_details; // 注意：axios 的响应数据在 response.data 中
      console.log("msg.value:", msg.value);
      user_id = response.user_id; // 同样，这里也是 response.data
      // 获取数据的总条数
      if (msg && msg.value && msg.value.length) {
        total.value = msg.value.length;
      } else {
        total.value = 0;
      }
      // 获取当前页的数据
      getPageData();
    })
    .catch(err => {
      // 请求失败的处理
      console.error(err);
    });
}

//获取全部数据
function getAllData() {
  console.log('getAllData')
  //清空输入的imputStr
  //请求全部的数据
  getData()
}

//获取当前页的数据
function getPageData() {
  //先把当前页面的数据清空
  tableData.value = []
  //获取当前页面的数据
  for (let i = (currentPage.value - 1) * pageSize.value; i < total.value; i++) {
    //遍历数据添加到tableData中
    tableData.value.push(msg.value[i])
    // console.log(msg.value[i])
    // console.log(tableData.value[i])
    //判断是否达到一页的要求
    if (tableData.value.length === pageSize.value) break
  }
}

//分页时修改每一页所展示的数据量
const handleSizeChange = (val) => {
  //修改当前每一页的数据条数
  pageSize.value = val
  //数据重新分页
  getPageData()
  console.log(`${val} items per page`)
}

//调整当前页的页码
const handleCurrentChange = (val) => {
  //修改当前页的页码
  currentPage.value = val
  //数据重新分页
  getPageData()
  console.log(`current page: ${val}`)
}


// 部署按钮
function deploy(project) {
  ElMessageBox.confirm('是否确认部署该项目？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里可以添加部署的逻辑
    console.log('部署项目:', project);
    loading.value = true
    axios.post('project/deploy', {
      git_address: project.project_git_url,
    }).then((response) => {
      if (response.code === 1) {
        console.log('部署成功:', response);
        loading.value = false
        // 处理成功的逻辑
        ElMessage({
          message: '项目部署成功',
          type: 'success'
        });
      } else {
        loading.value = false
        ElMessage({
          message: '项目部署失败' + response.message,
          type: 'error'
        });
      }
    }).catch((error) => {
      loading.value = false
      console.error('部署失败:', error);
      // 处理失败的逻辑
    });
  }).catch(() => {
    loading.value = false
    ElMessage({
      type: 'info',
      message: '已取消部署'
    });
  });
}
//查看项目端口
function viewPort(git_address) {
  console.log("git_address:", git_address)
  axios.get("project/getPort", {
    params: {
      git_address: git_address
    }
  }).then((response) => {
    if (response.code === 1) {
      ElMessage({
        message: '项目端口：' + response.url,
        type: 'success'
      });
      ElNotification({
        title: '项目基础url',
        message: response.url,
        type: 'success',
        duration: 0,
      })
    } else {
      ElMessage({
        message: '获取项目端口失败',
        type: 'error'
      });
      ElNotification({
        title: '获取项目端口失败',
        message: response.message,
        type: 'error',
        duration: 0,
      })
    }
  }).catch((error) => {
    console.error('获取项目端口失败:', error);
  });
}

//表单
const form = ref({
  project_name: '',
  project_owner_email: '',
  project_owner_html_url: '',
  project_git_url: '',
  repository_git_http_url: '',
  commits_url: '',
  project_language: '',
  last_updated: ''
});
let dialogTitle = ref('') //表单的标题
const dialogVisible = ref(false)  //控制显示表单
let isView = ref(false)
let isEdit = ref(false)

//关闭表单要处理的操作
function closeDialogForm(formName) {
  //清空表单上一次所展示的内容
  // 清空表单上一次所展示的内容
  form.value.project_name = '';
  form.value.project_owner_email = '';
  form.value.project_owner_html_url = '';
  form.value.project_git_url = '';
  form.value.repository_git_http_url = '';
  form.value.commits_url = '';
  form.value.project_language = '';
  form.value.last_updated = '';

  //关闭表单
  dialogVisible.value = false

  //初始化isView和isEdit的值是false
  isEdit.value = false
  isView.value = false

}

//查看一条排放数据明细
function viewEmission(row) {
  console.log("这一行的数据->row:", row)
  //修改标题
  dialogTitle.value = "团队信息详情"
  //修改isView变量
  isView.value = true
  //弹出表单
  dialogVisible.value = true
  //深拷贝表单对象
  Object.assign(form.value, JSON.parse(JSON.stringify(row)))
}


const dialogFormRef = ref(null)
// 定义一个方法来打开对话框
const addProject = () => {
  dialogFormRef.value.openDialog()
}

// 截断链接函数
const shortenUrl = (url) => {
  return url.length > 15 ? url.substring(0, 15) + '...' : url;
};


onMounted(() => {

  getData()

})


</script>

<script lang="js">
export default {
  name: 'UserProjectManagement',
};

</script>

<style scoped>
.items-center {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.between {
  display: flex;
  align-items: start;
  justify-content: space-between;
}
</style>